package test;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.lowkey.dataSource.DBControl;
import com.lowkey.tableInfo.TableInfo;
import com.lowkey.tools.Constant;

import net.sf.cglib.proxy.MethodInterceptor;//cglib的方法拦截器
import net.sf.cglib.proxy.MethodProxy;

public class Session implements MethodInterceptor {
	
	private Class c;
	private Serializable id;
	
	public void load(Class c ,Serializable id){
		 this.c = c;
		 this.id= id;
	 }

	//方法拦截的众多参数.proxy.invokeSuper是调用被代理类的这个方法. 
	@Override
	public Object intercept(Object object, Method method, Object[] args,MethodProxy proxy) throws Throwable {
		Object targetObj = object.getClass().newInstance();
		targetObj = setValue("bookname",targetObj);
		System.out.println(proxy.getSuperName());
		Object result = proxy.invokeSuper(targetObj,args);//讲被代理的那个对象赋值
		System.out.println(result);
		return result;
	}
	
	public Object setValue(String name,Object targetObj){
		Object  rsObject  = new Object();
		DBControl db = new DBControl();
		TableInfo table = Constant.TABLEMAP.get(c.getName());
		String sql  = "select * from " + table.getTableName()+" where "+table.getId().getColumn()+"="+id;
		System.out.println(sql);
		ResultSet rs = db.getData(sql);
		try {
			while(rs.next()){
				rsObject= rs.getObject(name);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		Class c = targetObj.getClass();
		try {
//			Field f = c.getField(name);
			Method m = c.getDeclaredMethod("set"+name.substring(0,1).toUpperCase()+name.substring(1), String.class);
			m.invoke(targetObj,rsObject.toString());
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return targetObj;
	}
}
